home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap17 / Metric.java < prev   
Encoding:
Java Source  |  1997-04-20  |  1.5 KB  |  59 lines

  1. import java.awt.*;
  2. import java.applet.Applet;
  3.  
  4. public class Metric extends Applet {
  5.    TextField tf;
  6.    TextField tf2;
  7.    double    convFactor;
  8.    String    toUnits;
  9.    String    fromUnits;
  10.  
  11.    public void init() {
  12.       String factor = getParameter("factor");
  13.       fromUnits = getParameter("from");
  14.       toUnits = getParameter("to");
  15.  
  16.       if (fromUnits == null || toUnits == null || factor == null) {
  17.          fromUnits = "inches";
  18.          toUnits = "cm";
  19.          convFactor = 2.56;         
  20.       } else {
  21.          try {
  22.             convFactor = new Double(factor).doubleValue();
  23.          } catch (NumberFormatException e) {
  24.             fromUnits = "inches";
  25.             toUnits = "cm";
  26.             convFactor = 2.56;       
  27.          }
  28.       }
  29.  
  30.       add(new Label("Convert " + fromUnits + " to " + toUnits + ":"));
  31.  
  32.       tf = new TextField(10);
  33.       add(tf);
  34.  
  35.       tf2 = new TextField(20);
  36.       tf2.disable();
  37.       tf2.setBackground(Color.gray);
  38.       add(tf2);
  39.    }
  40.  
  41.    public boolean action(Event e, Object what) {
  42.       if (e.target == tf) {
  43.          String s = tf.getText();
  44.          try {
  45.             double d = new Double(s).doubleValue();
  46.             double result = d * convFactor;
  47.             String toEntry = new Double(result).toString();
  48.             tf2.setText(toEntry + " " + toUnits);
  49.          } catch (NumberFormatException x) {
  50.             tf2.setText("Please enter a number.");
  51.             tf.setText("");
  52.          }
  53.          repaint();
  54.          return true;
  55.       }
  56.       return false;
  57.    }
  58. }
  59.